package com.jorado.apollo.service;

import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;

import java.util.HashMap;
import java.util.Map;

public class UserApiService extends AbstractApiService {

    public UserApiService(CloseableHttpClient client, BasicCookieStore cookieStore, String baseUrl) {
        super(client, cookieStore, baseUrl);
    }

    /**
     * 用户登陆
     *
     * @param userName
     * @param password
     * @return
     */
    public String login(String userName, String password) {
        checkNotEmpty(userName, "userName");
        checkNotEmpty(password, "password");
        try {
            String path = "signin";
            Map formDatas = new HashMap();
            formDatas.put("username", userName);
            formDatas.put("password", password);
            post(path, formDatas);
            for (Cookie cookie : cookieStore.getCookies()) {
                if (cookie.getName().equals("JSESSIONID")) {
                    return cookie.getValue();
                }
            }
            return "";
        } catch (Exception ex) {
            throw new RuntimeException(String.format("User login failed, userName:" + userName), ex);
        }
    }
}
